/**
 * Created by lihao on 2017/3/7.
 */
//接口服务
"use strict";
var Promise = require('bluebird');
var ApiService = require('./ApiService');

module.exports = function () {
    var shopCartList = [];
    var totalData = {
        totalAmount: 0,
        totalAmountNoShipment: 0,
        count: 0,
        countAll: 0
    };
    return {
        refresh: function (type) {
            var _this = this;
            if (type) shopCartList = [];
            return ApiService.getApi('shoppingCar', {})
                .then(ApiService.error)
                .then(function (data) {
                    if('/shopCart/index.html' == window.location.pathname){
                        return _this.JDStock(data)
                    }else {
                        return Promise.resolve(data);
                    }

                })
                .then(_this.setData)
                .then(function (status) {
                    return _this.total(true);
                });
        },
        //计算JD是否有货
        JDStock: function (data) {
            var _this = this;
            var JDItem = _.filter(data.list, {productMark: 'LEBOOK'});
            if(_.size(JDItem)){
                return new Promise(function (resolve, reject) {
                    var arrPro = _.map(_.groupBy(JDItem, 'areaId'),function (item) {
                        return item;
                    });
                    Promise.map(arrPro, function (list) {
                        var temp = _.transform(list, function (r, n, index) {
                            r['goodsList[' + index + '].skuId'] = n.productId;
                            r['goodsList[' + index + '].num'] = n.quantity;
                        }, {});
                        _.set(temp, 'area', list[0].areaId);
                        return _this.newStockInfoQuery(temp);
                    })
                    .then(function (itemData) {
                        resolve(_.flattenDeep(itemData));
                    })
                    .catch(function (error) {
                        resolve([]);
                    });

                }).then(function (itemData) {
                    var mixed = _.map(_.filter(data.list, {productMark: 'LEBOOK'}),function (item) {
                        var plusDef = {
                            remainNum:'0',
                            stockStateDesc:"有货"
                        };
                        var plus = _.find(itemData,{skuId:parseInt(item.productId)});
                        if(!_.isEmpty(plus)){
                            plusDef.remainNum = plus.remainNum;
                            plusDef.stockStateDesc = plus.stockStateDesc;
                        }
                        item = _.assign(item,plusDef);
                        return item;
                    });
                    data.list = _.reject(data.list, {productMark: 'LEBOOK'}).concat(mixed);
                    return Promise.resolve(data);
                });
            }else {
                return Promise.resolve(data);
            }
        },
        //请求JD有地区有货接口
        newStockInfoQuery: function (data) {
            return ApiService.getApi('stockInfoQuery', data)
                .then(ApiService.errorNoMsg)
                .then(function (res) {
                    return Promise.resolve(JSON.parse(res.data.result));
                })
                .catch(function (error) {
                    return Promise.reject(error)
                })
        },
        setList: function (data) {
            var _this = this;
            return _this.setData(data)
                .then(function (status) {
                    return _this.total(true);
                });
        },
        setData: function (data) {
            var _this = this;
            return new Promise(function (resolve, reject) {
                if (data.code == 1) {
                    shopCartList = _.chain(shopCartList)
                        .map(function (item) {
                            return _.omit(item, ['totalAmount','originalPrice','price','originalTotalPrice', 'totalAmountNoShipment', 'quantity']);
                        })
                        .thru(function (value) {
                            return _.defaultsDeep(value, data.list);
                        })
                        .map(function (item) {
                            if (!_.has(item, 'isChecked')) _.set(item, 'isChecked', true);
                            return item;
                        }).value();
                    resolve(true);
                } else {
                    layer.msg(data.message)
                        .then(function ($modal) {
                            reject(false);
                        });
                }
            });
        },
        getList: function () {
            return shopCartList;
        },
        inCart:function (id) {
            return _.isEmpty(_.filter(shopCartList,{productId:id.toString()}));
        },
        setChecked: function (specId) {
            shopCartList = _.chain(shopCartList).map(function (item) {
                if (item.specId == specId) _.set(item, 'isChecked', !item.isChecked);
                return item;
            }).value();
            this.total(true);
        },
        CheckAll: function (status) {
            shopCartList = _.chain(shopCartList).map(function (item) {
                _.set(item, 'isChecked', !status);
                return item;
            }).value();
            this.total(true);
        },
        add: function (id, count, specificationId, itemInfoId, priceCompare, productMark, areaId) {
            var _this = this;
            var addIndex = layer.load(1, {shade: [0.3, '#000'], scrollbar: false});
            return ApiService.postApi('shoppingCarUpdate', {
                productId: id,
                count: count,
                operType: 'add',
                specId: specificationId,
                itemInfoId: itemInfoId,
                priceCompare: priceCompare,
                productMark: productMark,
                areaId: areaId
            })
                .then(ApiService.error)
                .then(function (data) {
                    layer.close(addIndex);
                    return _this.refresh();
                });

        },
        update: function (id, count, specificationId, itemInfoId, productMark, areaId) {
            var _this = this;
            var addIndex = layer.load(1, {shade: [0.3, '#000'], scrollbar: false});
            return ApiService.postApi('shoppingCarUpdate', {
                productId: id,
                count: count,
                operType: 'update',
                specId: specificationId,
                itemInfoId: itemInfoId,
                productMark: productMark,
                areaId: areaId
            })
                .then(ApiService.error)
                .then(function (data) {
                    return new Promise(function (resolve) {
                        setTimeout(function () {
                            layer.close(addIndex);
                            resolve(_this.refresh());
                        }, 1000)
                    });
                });
        },
        del: function (items) {
            var _this = this;
            var delData = _.transform(items, function (r, n) {
                if (r['specId'] == undefined) {
                    r['specId'] = [];
                    r['productId'] = [];
                    r['productMark'] = [];
                }
                r['specId'].push(n.specId);
                r['productId'].push(n.productId);
                r['productMark'].push(n.productMark);
            }, {});
            var addIndex = layer.load(1, {shade: [0.3, '#000'], scrollbar: false});
            return ApiService.postApi('shoppingCarDel', {
                productIds: delData.productId.join(','),
                specIds: delData.specId.join(','),
                productMark: delData.productMark.join(','),
            })
                .then(ApiService.error)
                .then(function (data) {
                    shopCartList = _.reject(shopCartList, function (o) {
                        var count = _.filter(items, {productId: o.productId, specId: o.specId});
                        return _.size(count) > 0;
                    });
                    layer.close(addIndex);
                    return _this.refresh();
                });

        },
        delCheck: function () {
            var item = _.filter(shopCartList, 'isChecked');
            if(_.size(item)){
                return this.del(item);
            }else {
                return Promise.reject(new Error('请选择要删除的商品。'))
            }

        },
        compare: function () {
            var arrayId = _.filter(shopCartList, 'isChecked');
            return arrayId.map(function (item) {
                return item
            })
        },
        total: function (type) {
            return new Promise(function (resolve) {
                var countList = shopCartList;
                if (type) {
                    countList = _.filter(shopCartList, 'isChecked');
                }
                totalData = {
                    totalAmount: _.sum(countList, function (item) {
                        return parseFloat(_.has(item, 'totalAmount') ? parseFloat(item.totalAmount.replace(/,/g, '')) : 0);
                    }),
                    totalAmountNoShipment: _.sum(countList, function (item) {
                        return parseFloat(_.has(item, 'totalAmountNoShipment') ? parseFloat(item.totalAmountNoShipment.replace(/,/g, '')) : 0);
                    }),
                    count: type ? _.size(countList) : _.countBy(countList, 'quantity'),
                    countAll: _.sum(countList, 'quantity'),
                };
                resolve(totalData);
            });
        },
        getTotalData: function () {
            return totalData;
        },
        confirmOrder: function () {
            var _this = this;
            var itemInfoIds = _.transform(shopCartList, function (r, n) {
                if (n.isChecked) r.push(n.itemInfoId);
            }, []);
            var addIndex = layer.load(1, {shade: [0.3, '#000'], scrollbar: false});
            return ApiService.postApi('cartToPurchasingDemandSave', {
                itemInfoIds: itemInfoIds.join(','),
                deliveryWay: '',
                demandTime: '',
                demandType: '',
                memo: '',
                orderStatus: 'DRAFT',
                remark: '',
                title: '',
                totalAmount: _this.total().totalAmount
            })
                .then(ApiService.error)
                .then(function (data) {
                    layer.close(addIndex);
                    return Promise.resolve(data);
                })
                .catch(function (error) {
                    layer.close(addIndex);
                    return Promise.reject(error);
                });
        },
        getSelectIds: function () {
            var confirmId = _.keys(_.groupBy(_.filter(shopCartList, 'isChecked'), 'productId'));
            return Promise.resolve(confirmId);
        },
    }
}();